package com.shenghuai.bclient.stores.widget;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.NonNull;

import com.leige.mytimerpickdemo.R;
import com.shenghuai.bclient.stores.util.DensityUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class PickerView extends View {
    private static final int DRAW_WHAT = 1;
    private static final String HOUR = "hour";
    public static final float MARGIN_ALPHA = 2.8f;
    private static final String MINUTE = "minute";
    private static final String OTHER = "other";
    public static final float SPEED = 2.0f;
    public float HEIGHT_TEXT_SIZE_FACTOR = 4.0f;
    public float MAX_MIN_FACTOR = 2.0f;
    private ISelectTextSizeListener iSelectTextSizeListener;
    public boolean isDown = false;
    private boolean isInit = false;
    private boolean isUp = false;
    private int mCurrentSelected;
    private List<String> mDataList;
    private float mLastDownY;
    private float mMaxTextSize = 80.0f;
    private float mMinTextSize = 40.0f;
    public float mMoveLen = 0.0f;
    private Paint mPaint;
    private onSelectListener mSelectListener;

    public MyTimerTask mTask;
    private int mViewHeight;
    private int mViewWidth;
    private int selectColor;
    private float selectedTextSize;
    private Timer timer;
    private int unSelectColor;
    private int mMaximumFlingVelocity = 0;

    public static final int viewTypeHour = 1;
    public static int viewTypeMinute = 2;

    static class MyHandler extends Handler {

        final WeakReference<PickerView> ref;

        MyHandler(WeakReference<PickerView> ref) {
            this.ref = ref;
        }

        @Override
        public void handleMessage(@NonNull Message message) {

            PickerView pickerView = ref != null ? ref.get() : null;

            if (pickerView == null)
                return;

            if (message.what == DRAW_WHAT) {
                pickerView.invalidate();
                return;
            }
            if (Math.abs(pickerView.mMoveLen) < SPEED) {
                pickerView.mMoveLen = 0.0f;
                if (pickerView.mTask != null) {
                    pickerView.mTask.cancel();
                    pickerView.performSelect();
                }
            } else {
                pickerView.mMoveLen -= ((pickerView.mMoveLen / Math.abs(pickerView.mMoveLen)) * SPEED);
            }
            pickerView.invalidate();
        }
    }

    private Handler updateHandler;
    private String viewType;
    private VelocityTracker vt = null;

    public interface ISelectTextSizeListener {
        void onTextSize(float textSize);
    }

    public interface onSelectListener {
        void onSelect(String selectText);
    }

    public PickerView(Context context) {
        super(context);
        init();
    }

    public PickerView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }

    public void setOnSelectListener(onSelectListener onselectlistener) {
        this.mSelectListener = onselectlistener;
    }

    public void setiSelectTextSizeListener(ISelectTextSizeListener iSelectTextSizeListener2) {
        this.iSelectTextSizeListener = iSelectTextSizeListener2;
    }


    public void performSelect() {
        onSelectListener onselectlistener = this.mSelectListener;
        if (onselectlistener != null) {
            onselectlistener.onSelect(this.mDataList.get(this.mCurrentSelected));
        }
    }


    public void setData(List<String> list, int viewType) {
        this.mDataList = list;
        if (viewType == viewTypeHour) {
            this.viewType = HOUR;
        } else if (viewType == viewTypeMinute) {
            this.viewType = MINUTE;
        } else {
            this.MAX_MIN_FACTOR = 1.4f;
            this.HEIGHT_TEXT_SIZE_FACTOR = 5.0f;
            this.viewType = OTHER;
        }
        invalidate();
    }

    public void setSelected(int i) {
        this.mCurrentSelected = i;
        invalidate();
    }

    public int getCurrentSelected() {
        return this.mCurrentSelected;
    }

    public void setSelected(String str) {
        for (int i = 0; i < this.mDataList.size(); i++) {
            if (this.mDataList.get(i).equals(str)) {
                setSelected(i);
                return;
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        this.mViewHeight = getMeasuredHeight();
        this.mViewWidth = getMeasuredWidth();
        this.mMaxTextSize = ((float) this.mViewHeight) / this.HEIGHT_TEXT_SIZE_FACTOR;
        this.mMinTextSize = this.mMaxTextSize / this.MAX_MIN_FACTOR;
        this.isInit = true;
        invalidate();
    }

    private void init() {
        Resources resources = getResources();
        updateHandler = new MyHandler(new WeakReference<>(this));
        this.unSelectColor = resources.getColor(R.color.room_manager_drag_tip);
        this.selectColor = resources.getColor(R.color.title_color);
        this.timer = new Timer();
        this.mDataList = new ArrayList<>();
        this.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        this.mPaint.setStyle(Paint.Style.FILL);
        this.mPaint.setTextAlign(Paint.Align.CENTER);
        this.mPaint.setColor(this.selectColor);
        this.mMinTextSize = DensityUtils.INSTANCE.spToPx(30f);

        final ViewConfiguration configuration = ViewConfiguration.get(this.getContext());
        mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity();
    }


    public boolean dispatchTouchEvent(MotionEvent motionEvent) {
        getParent().requestDisallowInterceptTouchEvent(true);
        return super.dispatchTouchEvent(motionEvent);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (this.isInit) {
            drawData(canvas);
        }
    }

    private void drawData(Canvas canvas) {
        float parabola = parabola(((float) this.mViewHeight) / 5.0f, this.mMoveLen);
        float currentTextSize = ((this.mMaxTextSize - this.mMinTextSize) * parabola) + this.mMinTextSize;
        this.mPaint.setTextSize(currentTextSize);
        this.mPaint.setColor(getTextColorByScale(parabola));
        double d = this.mViewWidth;
        float centerX = (float) (d / 2.0d);
        double viewHeight = this.mViewHeight;
        double moveLen = this.mMoveLen;
        Paint.FontMetricsInt fontMetricsInt = this.mPaint.getFontMetricsInt();
        double scrollY = ((float) ((viewHeight / 2.0d) + moveLen));
        double bottom = fontMetricsInt.bottom;
        double top = fontMetricsInt.top;
        String str = this.mDataList.get(this.mCurrentSelected);
        setContentDescription(this.viewType + ":" + str);
        canvas.drawText(getAvailableText(str, this.mPaint), centerX, (float) (scrollY - ((bottom / 2.0d) + (top / 2.0d))), this.mPaint);
        drawOtherText(canvas, 1, -1);
        drawOtherText(canvas, 1, 1);
        if (currentTextSize > this.selectedTextSize && this.iSelectTextSizeListener != null) {
            this.selectedTextSize = currentTextSize;
            this.iSelectTextSizeListener.onTextSize(currentTextSize);
        }
    }

    private String getAvailableText(String str, Paint paint) {
        int width;
        if (!TextUtils.isEmpty(str) && paint != null && ((int) paint.measureText(str)) > (width = (getWidth() - getPaddingLeft()) - getPaddingRight())) {
            int measureText = width - ((int) paint.measureText("..."));
            int length = str.length();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length; i++) {
                String stringBuffer2 = sb.toString();
                sb.append(str.charAt(i));
                if (((int) paint.measureText(sb.toString())) > measureText) {
                    return stringBuffer2 + "...";
                }
            }
        }
        return str;
    }

    private void drawOtherText(Canvas canvas, int i, int i2) {
        float f = (float) i2;
        float f2 = (this.mMinTextSize * MARGIN_ALPHA * ((float) i)) + (this.mMoveLen * f);
        float parabola = parabola(((float) this.mViewHeight) / 5.0f, f2);
        float f3 = this.mMaxTextSize;
        float f4 = this.mMinTextSize;
        this.mPaint.setTextSize(((f3 - f4) * parabola) + f4);
        this.mPaint.setColor(getTextColorByScale(parabola));
        double d = this.mViewHeight;
        double d2 = f * f2;
        Paint.FontMetricsInt fontMetricsInt = this.mPaint.getFontMetricsInt();
        double d3 = (float) ((d / 2.0d) + d2);
        double d4 = fontMetricsInt.bottom;
        double d5 = fontMetricsInt.top;
        float f5 = (float) (d3 - ((d4 / 2.0d) + (d5 / 2.0d)));
        int i3 = this.mCurrentSelected;
        int i4 = (i * i2) + i3;
        if (i3 == this.mDataList.size() - 1 && i2 == 1) {
            i4 = 0;
        } else if (this.mCurrentSelected == 0 && i2 == -1) {
            i4 = this.mDataList.size() - 1;
        }
        String avaliableText = getAvailableText(this.mDataList.get(i4), this.mPaint);
        double d6 = this.mViewWidth;
        canvas.drawText(avaliableText, (float) (d6 / 2.0d), f5, this.mPaint);
    }

    private int getTextColorByScale(float scale) {
        int red = Color.red(this.unSelectColor);
        int green = Color.green(this.unSelectColor);
        int blue = Color.blue(this.unSelectColor);
        return Color.rgb((int) (red + ((Color.red(this.selectColor) - red) * scale)),
                (int) (green + ((Color.green(this.selectColor) - green) * scale)),
                (int) (blue + ((Color.blue(this.selectColor) - blue) * scale)));
    }

    private float parabola(float f, float f2) {
        float pow = (float) (1.0d - Math.pow((f2 / f), 2.0d));
        return Math.max(pow, 0.0f);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int mask = event.getActionMasked();
        if (mask == MotionEvent.ACTION_DOWN) {
            isDown = true;
            isUp = false;
            if (vt != null) {
                vt.clear();
            }
            vt = VelocityTracker.obtain();
            vt.addMovement(event);
            doDown(event);
            return true;
        } else if (mask == MotionEvent.ACTION_UP || mask == MotionEvent.ACTION_CANCEL) {
            isUp = true;
            isDown = false;
            float yVelocity = vt.getYVelocity();
            int flag = yVelocity > 0 ? 1 : (yVelocity == 0 ? 0 : -1);
            if (flag != 0) {
                up((int) yVelocity);
                vt.recycle();
                vt = null;
                return true;
            }
        } else if (mask == MotionEvent.ACTION_MOVE) {//2
            vt.addMovement(event);
            vt.computeCurrentVelocity(1000, mMaximumFlingVelocity);
            doMove(event);
            return true;
        }
        return super.onTouchEvent(event);
    }

    private void doDown(MotionEvent motionEvent) {
        MyTimerTask myTimerTask = this.mTask;
        if (myTimerTask != null) {
            myTimerTask.cancel();
            this.mTask = null;
        }
        this.mLastDownY = motionEvent.getY();
    }

    private void doMove(MotionEvent event) {
        this.mMoveLen += event.getY() - this.mLastDownY;
        float moveLen = this.mMoveLen;
        float mMinTextSize = this.mMinTextSize;
        if (moveLen > (mMinTextSize * MARGIN_ALPHA) / 2.0f) {
            this.mCurrentSelected--;
            if (this.mCurrentSelected < 0) {
                this.mCurrentSelected = this.mDataList.size() - 1;
            }
            this.mMoveLen -= this.mMinTextSize * MARGIN_ALPHA;
        } else if (moveLen < (mMinTextSize * -MARGIN_ALPHA) / 2.0f) {
            this.mCurrentSelected++;
            if (this.mCurrentSelected > this.mDataList.size() - 1) {
                this.mCurrentSelected = 0;
            }
            this.mMoveLen += this.mMinTextSize * MARGIN_ALPHA;
        }
        this.mLastDownY = event.getY();
        invalidate();
    }

    public void doUp() {
        if ((Math.abs(this.mMoveLen)) < 0.0001) {
            this.mMoveLen = 0.0f;
            return;
        }
        MyTimerTask myTimerTask = this.mTask;
        if (myTimerTask != null) {
            myTimerTask.cancel();
            this.mTask = null;
        }
        this.mTask = new MyTimerTask(this.updateHandler);
        this.timer.schedule(this.mTask, 0, 5);
    }

    private void up(int y) {
        int abs = Math.abs(y) / 20;
        if (abs > 4000) {
            abs = 4000;
        }
        int i2 = y / 100;
        if (i2 > 80) {
            i2 = 80;
        } else if (i2 < -80) {
            i2 = -80;
        }
        final ValueAnimator ofInt = ValueAnimator.ofInt(i2, 0);
        ofInt.setInterpolator(new DecelerateInterpolator());
        ofInt.setDuration(abs);
        ofInt.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                if (PickerView.this.isDown) {
                    ofInt.cancel();
                } else {
                    PickerView.this.finishing((Integer) valueAnimator.getAnimatedValue());
                }
            }
        });
        ofInt.addListener(new Animator.AnimatorListener() {
            public void onAnimationCancel(Animator animator) {
            }

            public void onAnimationRepeat(Animator animator) {
            }

            public void onAnimationStart(Animator animator) {
            }

            public void onAnimationEnd(Animator animator) {
                PickerView.this.doUp();
            }
        });
        ofInt.start();
    }


    public void finishing(int i) {
        this.mMoveLen += (float) i;
        float f = this.mMoveLen;
        float f2 = this.mMinTextSize;
        if (f > (f2 * MARGIN_ALPHA) / 2.0f) {
            this.mCurrentSelected--;
            if (this.mCurrentSelected < 0) {
                this.mCurrentSelected = this.mDataList.size() - 1;
            }
            this.mMoveLen -= this.mMinTextSize * MARGIN_ALPHA;
        } else if (f < (f2 * -MARGIN_ALPHA) / 2.0f) {
            this.mCurrentSelected++;
            if (this.mCurrentSelected > this.mDataList.size() - 1) {
                this.mCurrentSelected = 0;
            }
            this.mMoveLen += this.mMinTextSize * MARGIN_ALPHA;
        }
        this.updateHandler.sendEmptyMessage(1);
    }

    static class MyTimerTask extends TimerTask {
        Handler handler;

        MyTimerTask(Handler handler2) {
            this.handler = handler2;
        }

        public void run() {
            this.handler.sendMessage(handler.obtainMessage());
        }
    }
}